package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.LimitParamTypeEnum;
import cc.rengu.redp.bizimpl.enums.SettleAccTypeEnum;
import cc.rengu.redp.bizimpl.igas.controller.PDstChannelInfoController;
import cc.rengu.redp.bizimpl.igas.domain.PDstChannelInfo;
import cc.rengu.redp.bizimpl.igas.domain.PDstTxnAuthCfg;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelInfoService;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BTxnLimitCfg;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.service.BTxnLimitCfgService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpOrganizationService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.RedpUpmpUtil;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Api(tags = "交易限额限次配置管理")
@RestController
@RequestMapping("/admin/mcmp/bTxnLimitCfg")
public class BTxnLimitCfgController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(PDstChannelInfoController.class);
    @Autowired
    private BTxnLimitCfgService bTxnLimitCfgService;
    @Autowired
    IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpOrganizationService upmpOrganizationService;
    @Autowired
    private PDstChannelInfoService pDstChannelInfoService;
    @GetMapping
    public Map<String, Object> list(QueryRequest request, BTxnLimitCfg entity) {
        return getDataTable(this.bTxnLimitCfgService.findByPage(request, entity));
    }



    @RequiresPermissions("pDstChannel:info")
    @RequestMapping(value = "/editFromChnl", method = RequestMethod.GET)

    public BTxnLimitCfg editFromChnl(PDstTxnAuthCfg model, HttpServletRequest request) throws RedpException {

        String optFlag = request.getParameter("optFlag");
        if (Common.isBlank(optFlag)) {
            logger.error("请求参数(optFlag)异常!");
            throw new RedpException("请求参数异常！");
        }
        String instId = request.getParameter("instId");
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(instId);
        String crtOrgId=user.getOrgCode();
        if(Common.isBlank(instId)){
            instId=user.getInstId();
        }
        if(user.isAdmin()){
            crtOrgId=user.getOrgCode();
        }

        PDstChannelInfo pDstChannelInfo = new PDstChannelInfo();
        String dstChannelId = request.getParameter("dstChannelId");
        pDstChannelInfo = pDstChannelInfoService.findOne(instId,dstChannelId);
        if (Common.isBlank(pDstChannelInfo)) {
            logger.error("根据唯一索引[{},{}]没有找到指定通道数据！",instId,dstChannelId);
            throw new RedpException("根据唯一索引没有找到指定通道数据！");
        }
        String channelTxn =  request.getParameter("channelTxn");
        String limitInst="";
        if(Common.isNotBlank(channelTxn)){
            limitInst=dstChannelId+ BusinessContainer.LIMIT_PARAM_VALUE_SPLIT+channelTxn;
        }else{
            limitInst=dstChannelId;
        }
        BTxnLimitCfg bTxnLimitCfg=bTxnLimitCfgService.findByUniqueIndex(instId, LimitParamTypeEnum.LIMIT_CHNL_TXN.getType(), limitInst, SettleAccTypeEnum.ALL_ACCOUNT.getType());
        if(bTxnLimitCfg==null){
            bTxnLimitCfg = new BTxnLimitCfg();
            bTxnLimitCfg.setInstId(pDstChannelInfo.getInstId());
            bTxnLimitCfg.setLimitType(LimitParamTypeEnum.LIMIT_CHNL_TXN.getType());
            bTxnLimitCfg.setLimitInst(limitInst);
            bTxnLimitCfg.setLimitAcctType(SettleAccTypeEnum.ALL_ACCOUNT.getType());
            bTxnLimitCfg.setStatus(IgasYesOrNoEnum.Yes.getType());
            bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
            bTxnLimitCfg.setCrtOrgId(crtOrgId);
            bTxnLimitCfg.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        }
        bTxnLimitCfg.setOptFlag(optFlag);

        request.setAttribute("entity",bTxnLimitCfg);
        request.setAttribute("optFlag",optFlag);
        request.setAttribute("instId",instId);
        request.setAttribute("dstChannelId",dstChannelId);
        return bTxnLimitCfg;
    }

    @GetMapping(value = "/editFromChnlTxn")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "channelTxn", value = "调用通道交易码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map<String, Object> editFromChnlTxn(@NotBlank(message = "{required}") String optFlag, @NotBlank(message = "{required}") String dstChannelId,
                                               @NotBlank(message = "{required}") String channelTxn, @NotBlank(message = "{required}") String instId) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String crtOrgId = user.getOrgCode();
        if (user.isAdmin()) {
            UpmpOrganization headOrg = upmpOrganizationService.getHeadOrgByCode(instId);
            crtOrgId = headOrg == null ? user.getOrgCode() : headOrg.getOrgCode();
        }

        PDstChannelInfo pDstChannelInfo = new PDstChannelInfo();
        pDstChannelInfo = pDstChannelInfoService.findOne(instId, dstChannelId);
        if (Common.isBlank(pDstChannelInfo)) {
            log.error("根据唯一索引[{},{}]没有找到指定通道数据！", instId, dstChannelId);
            throw new RedpException("根据唯一索引没有找到指定通道数据！");
        }
        String limitInst = "";
        if (Common.isNotBlank(channelTxn)) {
            limitInst = dstChannelId + BusinessContainer.LIMIT_PARAM_VALUE_SPLIT + channelTxn;
        } else {
            limitInst = dstChannelId;
        }
        List<BTxnLimitCfg> bTxnLimitCfgs = bTxnLimitCfgService.findByPDstChannelInfo(instId, LimitParamTypeEnum.LIMIT_CHNL_TXN.getType(), limitInst);
        BTxnLimitCfg bTxnLimitCfg = bTxnLimitCfgService.findByUniqueIndex(instId, LimitParamTypeEnum.LIMIT_CHNL_TXN.getType(), limitInst, SettleAccTypeEnum.ALL_ACCOUNT.getType());
        if (bTxnLimitCfg == null) {
            bTxnLimitCfg = new BTxnLimitCfg();
            bTxnLimitCfg.setInstId(pDstChannelInfo.getInstId());
            bTxnLimitCfg.setLimitType(LimitParamTypeEnum.LIMIT_CHNL_TXN.getType());
            bTxnLimitCfg.setLimitInst(limitInst);
            bTxnLimitCfg.setLimitAcctType(SettleAccTypeEnum.ALL_ACCOUNT.getType());
            bTxnLimitCfg.setStatus(IgasYesOrNoEnum.Yes.getType());
            bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
            bTxnLimitCfg.setOprId(user.getId());
            bTxnLimitCfg.setCrtOrgId(crtOrgId);
            bTxnLimitCfg.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        }
        bTxnLimitCfg.setOptFlag(optFlag);
        result.put("entity", bTxnLimitCfg);
        result.put("optFlag", optFlag);
        result.put("instId", instId);
        result.put("dstChannelId", dstChannelId);
        result.put("channelTxn", channelTxn);
        return result;
    }

    @RequiresPermissions("pDstChannel:info")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult editSave(@ModelAttribute("bTxnLimitCfg") BTxnLimitCfg entity, HttpServletRequest request) throws RedpException {
       return bTxnLimitCfgService.saveData(entity, request);
    }


    @GetMapping("/mchntLevel")
    public OperationResult mchntLevel(@RequestParam("instId") String instId, @RequestParam("mchntNo") String mchntNo) {
        return bTxnLimitCfgService.getMchntLevel(instId, mchntNo);
    }

    /**
     * 停用商户等级限额配置
     */
    @RequiresPermissions("商户限额管理:商户等级限额管理")
    @ResponseBody
    @RequestMapping(value = "stopBTxnLimit", method = RequestMethod.POST)
    public OperationResult stopBTxnLimit(HttpServletRequest request,BTxnLimitCfg req) {

//        try {
//           merchantGradeQuotalManagerService.stopBTxnLimit(request,req);
//        }catch (RedpException e) {
//            log.error("保存限额信息操作时系统异常:[{}]", e);
//            return OperationResult.buildFailureResult("保存限额信息操作时系统异常:"+e.getMessage());
//
//        }  catch (Exception e) {
//            log.error("保存限额操作信息时系统异常:[{}]", e);
//            return OperationResult.buildFailureResult("保存限额操作信息时系统异常:请联系管理员");        }
        return OperationResult.buildSuccessResult();
    }

}

